import logging
from datetime import datetime

import psutil
from django.shortcuts import render
import os
import platform


# Create your views here.

def index(request):
    try:
        # posix.uname_result(sysname='Darwin', nodename='fandeMacBook-Pro.local', release='20.3.0', version='Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', machine='x86_64')
        data = os.uname()  # linux和mac系统执行的内容
        sys_name = data.nodename
        kernel_name = data.sysname
    except Exception as e:
        # uname_result(system='Darwin', node='fandeMacBook-Pro.local', release='20.3.0', version='Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', machine='x86_64', processor='i386')
        data = platform.uname()  # mac和windows执行的内容
        sys_name = data.node
        kernel_name = data.system
    kernel_no = data.release
    kernel_version = data.version
    sys_framework = data.machine
    boot_time = datetime.fromtimestamp(psutil.boot_time())
    now_time = datetime.now()
    logging.debug(now_time, boot_time)
    up_time = now_time - boot_time
    # 返回局部变量信息, 字典数据类型{'sys_name':sys_name, 'kernel_name':kernel_name}
    # print(locals())
    return render(request, 'index.html', locals())


def user(request):
    return render(request, 'user.html')


def cpu(request, chart=None):
    if chart == 'line':
        return  render(request, 'cpu-line.html')
    if chart == 'pie':
        return  render(request, 'cpu-pie.html')
    # 逻辑cpu个数和物理cpu个数
    logical_core_num = psutil.cpu_count()
    physical_core_num = psutil.cpu_count(logical=False)

    # 平均负载，返回一个元组(1min_avg_load, 5min_avg_load, 15_avg_load)
    try:
        load_avg = os.getloadavg()  # Raises OSError if the load average was unobtainable.
    except Exception as e:
        load_avg = ['', '', '']

    # cpu使用百分比，scputimes(user=0.0, nice=0.0, system=0.0, idle=0.0)
    cpu_time_percent = psutil.cpu_times_percent()

    return render(request, 'cpu.html', locals())


def memory(request):
    return render(request, 'memory.html')


def disk(request):
    return render(request, 'disk.html')


def network(request):
    return render(request, 'network.html')


def process(request):
    return render(request, 'process.html')
